package com.miao.shop.controller;

import com.alibaba.fastjson.JSON;
import com.miao.common.entity.R;
import com.miao.common.entity.pojo.Product;
import com.miao.common.entity.search.ProductES;
import com.miao.shop.service.ShopProductService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author MiaoWenqing
 * @description: 商品
 * @date 2021/2/15 20:54
 */
@RestController
@RequestMapping("/common/product")
public class ShopProductController {

    @Resource
    private ShopProductService shopProductService;

    @Resource(name = "RestHighLevelClient")
    private RestHighLevelClient restHighLevelClient;


    /**
     * 根据商品id获取 商品信息
     * @param proId 商品id
     * @return R
     */
    @GetMapping("/get")
    public R getOne(String proId){
        Product product = this.shopProductService.getById(proId);
        if (null==product){
            return R.error("商品不存在");
        }
        return R.ok(product);
    }

    /**
     * 商品搜索
     * @param condition 关键词
     * @param type 1 类型搜索 还是 2 标题搜索
     * @return
     */
    @GetMapping("search")
    public R searchPro(String condition,String type){

        SearchRequest searchRequest = new SearchRequest("miaoshop");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        if ("2".equals(type)){
            searchSourceBuilder.query(QueryBuilders.termQuery("proTitle",condition));
        }else if ("1".equals(type)){
            searchSourceBuilder.query(QueryBuilders.termQuery("proClass",condition));
        }


        searchRequest.source(searchSourceBuilder);

        SearchResponse search = null;
        try {
            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ArrayList<ProductES> products = new ArrayList<>();
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit : hits) {
            products.add(JSON.parseObject(hit.getSourceAsString(),ProductES.class));
        }
        return R.ok(products);


    }







}
